import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { useModel } from 'umi';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import { BarChart, MapChart } from 'echarts/charts';
import {
  GridComponent,
  ToolboxComponent,
  TooltipComponent,
  TitleComponent,
  VisualMapComponent,
  DatasetComponent,
} from 'echarts/components';
import { CanvasRenderer, SVGRenderer } from 'echarts/renderers';
import { InsureData, ChartData } from '../data';
import { queryInsureData } from '../service';

import styles from '../index.less';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  MapChart,
  BarChart,
  CanvasRenderer,
  SVGRenderer,
  ToolboxComponent,
  VisualMapComponent,
]);

type InsuranceProps = {
  year: number;
  geoJson: { [key: string]: any };
};

const colors = ['#0DEBFF', '#52FFDC', '#94BEFF', '#5289FF'];

const Insurance: React.FC<InsuranceProps> = (props) => {
  echarts.registerMap('MapChat', props.geoJson);

  const [caseData, setCaseData] = useState<ChartData[] | []>([]);
  const [mapData, setMapData] = useState<ChartData[] | []>([]);
  const [orderData, setOrderData] = useState<ChartData[] | []>([]);
  const [totalData, setTotalData] = useState<ChartData[] | []>([]);

  // 页面初始化
  useEffect(() => {}, []);

  useEffect(() => {
    queryData(props.year);
  }, [props.year]);

  const { initialState } = useModel('@@initialState');

  const areaId = initialState?.currentUser?.areaId;
  const queryData = (year: number) => {
    queryInsureData({ year, areaId }).then(
      (rsp: { code: number; msg: string; data: InsureData }) => {
        if (rsp.code != 200) {
          message.error(rsp.msg);
          return;
        }
        const { caseData, mapData, orderData, totalData } = rsp.data;
        setCaseData(caseData);
        setMapData(mapData);
        setOrderData(orderData);
        setTotalData(totalData);
      },
    );
  };

  // 地图
  const mapChart = (
    <ReactEChartsCore
      echarts={echarts}
      style={{ height: '100%' }}
      option={{
        series: [
          {
            name: '...',
            type: 'map',
            map: 'MapChat',
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            itemStyle: {
              areaColor: 'rgba(255,255,255,0)',
              borderColor: '#43B4DF',
              borderWidth: 1.5,
            },
            label: {
              show: true,
              formatter: (params) => {
                return (
                  (params.data &&
                    [`{a|${params.data.value}}`, '{b| }'].join('\n')) ||
                  ''
                );
              },
              rich: {
                a: {
                  color: '#3BF2FF',
                  fontFamily: 'SF Pro Display Heavy Italic',
                  fontSize: 26,
                  fontWeight: 400,
                },
                b: {
                  backgroundColor: {
                    image: require('../../../assets/location2.gif'),
                  },
                  // lineHeight: 10,
                  height: 62,
                  width: 104,
                },
              },
            },
            data: mapData.map((d: ChartData) => ({
              value: d.dataValue,
              name: d.dataTitle,
            })),
          },
        ],
      }}
      notMerge={true}
      lazyUpdate={true}
      theme={'theme_name'}
      opts={{ renderer: 'svg' }}
    />
  );

  // 保单数量柱状图
  const insuranceChart = orderData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        grid: {
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          splitLine: {
            show: true,
            interval: 100,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#48EAF0',
            fontSize: 14,
          },
          axisLine: {
            lineStyle: {
              color: '#5BADC2',
            },
          },
          data: orderData.map((d: ChartData) => d.dataTitle),
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#5BADC2',
            fontSize: 14,
          },
        },
        series: [
          {
            label: {
              show: true,
              position: 'top',
              color: '#0DEBFF',
            },
            data: orderData.map((d: ChartData, index: number) => ({
              value: d.dataValue,
              itemStyle: {
                color: colors[index],
              },
            })),
            type: 'bar',
          },
        ],
      }}
      style={{ height: '80%' }}
    />
  );

  // 案件数量柱状图
  const caseChart = caseData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        grid: {
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          splitLine: {
            show: true,
            interval: 100,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#48EAF0',
            fontSize: 14,
            margin: 13,
          },
          axisLine: {
            lineStyle: {
              color: '#5BADC2',
            },
          },
          data: caseData.map((d: ChartData) => d.dataTitle),
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#5BADC2',
            fontSize: 14,
            margin: 15,
          },
        },
        series: [
          {
            label: {
              show: true,
              position: 'top',
              color: '#0DEBFF',
            },
            data: caseData.map((d: ChartData, index: number) => ({
              value: d.dataValue,
              itemStyle: {
                color: colors[index],
              },
            })),
            type: 'bar',
          },
        ],
      }}
      style={{ height: '80%', width: 414 }}
    />
  );

  return (
    <>
      {/* 标题 */}
      <div className={styles.header}>
        <div className={styles.title}>
          区域：{initialState?.currentUser?.areaName}
        </div>
      </div>

      {/* 总数 */}
      <div className={styles.countContainer + ' ' + styles.layout}>
        {totalData.map((d: ChartData, index: number) => (
          <div key={index} className={styles.countItem}>
            <div className={styles.countTitle}>{d.dataTitle}</div>
            <div className={styles.countNum}>{d.dataValue}</div>
            <img
              className={styles.countBg}
              src={require('../../../assets/count-bg.png')}
            />
          </div>
        ))}
      </div>

      {/* 地图 */}
      <div className={styles.mapContainer + ' ' + styles.layout}>
        <div className={styles.mapTitle}>
          <img
            className={styles.mapTitleImg}
            src={require('../../../assets/title-left.png')}
          />
          <div className={styles.mapTitleLable}>单件：保单数/理赔案件数</div>
          <img
            className={styles.mapTitleImg}
            src={require('../../../assets/title-right.png')}
          />
        </div>
        {mapChart}
      </div>

      {/* 左边 */}
      <div className={styles.left + ' ' + styles.layout}>
        <div className={styles.leftCard + ' ' + styles.lg}>
          <div className={styles.cardTitle}>{props.year}年投保</div>
          <div className={styles.cardSubTitle}>保单数量</div>
          {insuranceChart}
        </div>
      </div>

      {/* 右边 */}
      <div className={styles.right + ' ' + styles.layout}>
        <div className={styles.rightCard + ' ' + styles.lg}>
          <div className={styles.cardTitle}>{props.year}年理赔</div>
          <div className={styles.cardSubTitle}>案件数量</div>
          {caseChart}
        </div>
      </div>
    </>
  );
};

export default Insurance;
